<?php

namespace common\models\info;

use common\component\BaseActiveRecord;
use common\component\Constant;
use common\component\WebUser;
use common\models\base\Admin;
use common\models\base\AttachmentService;
use common\utils\CommonUtil;
use frontend\service\TagService;
use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "{{%zt_article}}".
 *
 * @property int $id
 * @property string $title 标题
 * @property string $summary 摘要
 * @property string $cover_image 封面图片
 * @property string $cate_id 分类id
 * @property string $source 来源
 * @property int $is_rec 推荐(0不推荐1热门)
 * @property int $status 状态(-1未通过 0草稿 1未审核 2通过)
 * @property int $sort 排序
 * @property string $content 内容详情
 * @property int $collect_total 收藏数量
 * @property int $comment_total 评论数量
 * @property int $like_total 点赞数量
 * @property int $updated_at 修改时间
 * @property int $created_at 创建时间
 * @property int $release_at 发布时间
 *  * @property int $author_id 作者
 */
class Article extends BaseActiveRecord
{

    const EVENT_AFTER_RELEASE = "after_release";  //文章发布之后
    const EVENT_BEFORE_RELEASE = "before_release"; //文章发布之前

    /**
     * @var
     */
    public $tag_str;
    public $category_id_str;
    public $reason;  //理由

    public $transOjb; //开启一个事务


    const STATUS_UNPASS  = -1;  //未通过
    const STATUS_DRAFT = 0;    //草稿
    const STATUS_UNAUDITED  = 1;  //未审核
    const STATUS_PASS = 2;     //通过



    const REC_GENERAL = 0;//不推荐
    const REC_INDEX = 1;//首页推荐
    const REC_HOT = 2; //热门


    public static $recArrayList = [
        self::REC_GENERAL => '不推荐',
        self::REC_INDEX => '首页',
        self::REC_HOT  => '热门',
    ];


    public static $statusDropdownList = [
        ['id'=>self::STATUS_DRAFT,'text'=>"请选择文章状态"],
        ['id'=>self::STATUS_UNPASS,'text'=>"未通过"],
        ['id'=>self::STATUS_UNAUDITED,'text'=>"待审核"],
        ['id'=>self::STATUS_PASS,'text'=>"审核通过"],
    ];

    public static $statusArrayList = [
        self::STATUS_UNPASS=>"未通过",
        self::STATUS_DRAFT => "草稿",
        self::STATUS_UNAUDITED=>"待审核",
        self::STATUS_PASS=>"审核通过",
    ];
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{zt_article}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['is_rec','status','sort','author_id', 'collect_total','comment_total','like_total','updated_at', 'created_at'], 'integer'],
            [['content','tag_str','cate_id','mark_content'], 'string'],
            [['title'], 'string', 'max' => 127,"message"=>"标题超出指定长度"],
            ['title','required','message'=>'标题不能为空'],
            [['summary', 'cover_image','cate_id'], 'string', 'max' => 255],
            [['sort'],'filter','filter'=>function ($value) {
                        return empty($value) ? 0 :$value;
            }]
        ];
    }

    /**
     * 获取文章话题标签
     * @return \yii\db\ActiveQuery
     */
    public function getOwnTags() {
        return $this->hasMany(TagsRelation::className(),['object_id'=>$this->id]);
    }

    public function ownTagsList() {
        $result = [];
        $tagRelations = TagsRelation::find()->where(['object_id'=>$this->id])->all();
        foreach ($tagRelations as $item) {
            $tag = Tags::findOne($item['tag_id']);
            if (!$tag) continue;
            $result[] = ['id'=>$tag->id,'text'=>$tag->tag_name];
        }
        return $result;
    }

    public function getArticleTags() {
        return $this->ownTagsList();
    }


    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'summary' => '导语',
            'cover_image' => '封面图',
            'cate_id' => '分类',
            'is_rec' => '推荐',
            'status' => '状态',
            'sort' => '排序',
            'author_id'=>'作者id',
            'content' => '内容',
            'mark_content'=>'markdown的内容',
            'collect_total' => '收藏数',
            'like_total' => '赞同量',
            'comment_total' => '评论数',
            'view_total' => '浏览量',
            'updated_at' => '更新时间',
            'created_at' => '创建时间',
            'release_at' => '发布时间',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_at'],
                    self::EVENT_BEFORE_UPDATE => ['updated_at']
                ]
            ]
        ];
    }


    public function afterFind()
    {
        parent::afterFind();
            $this->ui();
    }

    public function ui() {
        $this->ui["cate_id"] = Category::getArticleCateData($this->cate_id)?implode(',',Category::getArticleCateData($this->cate_id)):'';
        $this->ui["status"] = $this->status?self::$statusArrayList[$this->status]:0;
        $this->ui["created_at"] = date("Y-m-d H:i:s",$this->created_at);
        $this->ui["author_name"] = Admin::getFieldById($this->author_id,'username');
        $this->ui["updated_at"] = date("Y-m-d H:i:s",$this->updated_at);
        $this->ui["release_at"] = $this->release_at?date("Y-m-d H:i:s",$this->release_at):'';
        $this->ui['tag_ar'] = TagsRelation::getTagInfoByArtId($this->id);
        $this->ui['tag_list_ar'] = json_encode(TagsRelation::getTagInfoByArtId($this->id));
        $tag = '';
        $data = TagsRelation::getTagInfoByArtId($this->id);
        if($data){
            $tagArr = array_column($data,'text');
            $tag =  implode($tagArr,',');
        }

        $this->ui['tags_name'] = $tag;

    }
    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
        return false;
       }
        if ($insert) {
            $this->updated_at = $this->created_at;
        }
        if ($this->status==self::STATUS_PASS) {
            $release_at = self::getFieldById($this->id,'release_at');
//            $this->content = ArticleService::addTagUrlNew($this->content);  #审核通过add Tag
            if(!$release_at && !$this->release_at) {
                $this->release_at = time(); //文章发布时间
            }
        }
        if (empty($this->content)) {
            $this->addError("content","文章内容不能为空");
            return false;
        }
        return true;
    }

    public function afterSave($insert, $changedAttributes)
    {

        // 更新标签
        $data = !empty($this->tag_str) ? json_decode($this->tag_str,true) : [];
        $tagIds = Tags::refreshTagsByArticle($this->id,$data,$this->status,$changedAttributes);


        //更新文章分类(category_id_str)
        $cate_arr = !empty($this->cate_id) ? explode(',',$this->cate_id) : [];
        CategoryRelation::insertInto($this->id,$cate_arr);
        parent::afterSave($insert, $changedAttributes);
    }
    public function dataListTable($post) {
        //请求参数组装
        $where = ["and"];
        if (isset($post['title']) && !empty($post['title'])) {
            $where[] = ['like','title',trim($post['title'])];
        }
        if (isset($post['start']) && $post['start']) {
            $where[] = ['>=','release_at',strtotime($post['start'])];
        }
        if (isset($post['end']) && $post['end']) {
            $where[] = ['<','release_at',strtotime($post['end'])+86400];
        }
        if (isset($post['status']) && $post['status'] != 0) {
            $where[] =['=','status',$post['status']];
        } else {
            //显示指定的状态
            $where[] = ['in','status',[self::STATUS_UNPASS,self::STATUS_UNAUDITED,self::STATUS_PASS]];
        }
        $query = self::find()->where($where);
        $dataArr = self::table($query,$post);
        return $dataArr;
    }

    /**
     * @param $id
     * 获取上一篇文章和下一篇文章
     */
    public static function getSimilarArticle($id){
        $data = static::find()->Where(['<',"id",$id])->asArray()->limit(1)->one();
        $data1 = static::find()->andWhere(['>',"id",$id])->asArray()->limit(1)->one();
        if(count($data))$data['link'] = CommonUtil::generateUrl($data['id'],Constant::ROUTE_ARTICLE);   //文章标题url
        if(count($data1))$data1['link'] = CommonUtil::generateUrl($data1['id'],Constant::ROUTE_ARTICLE);   //文章标题url
        $result['prev'] = $data;
        $result['next'] = $data1;
        return  $result;
    }

    /**
     * 实例化模型对像
     * @param $id
     * @return BaseActiveRecord|null|static
     */
    public static function modelById($id) {
        if (!$id) {
            $model = new self();
        }
        else {
            $model = static::findOne($id);
        }
        return $model;
    }



    public static function categoryDropdownList() {
        $result = [
            ["id"=>0,"text"=>"请选择分类"]
        ];
        $data = Category::find()->where(['status'=>Category::STATUS_ENABLE])->orderBy("sort ASC")->asArray()->all();
        if ($data) {
            foreach ($data as $item) {
                $result[] = ['id'=>$item['id'],'text'=>$item['cate_name']];
            }
        }
        return $result;
    }


    public static function getFieldById($id,$field) {
        $data = self::loadRowData($id);
        if (is_array($field)) {
            $result = [];
            foreach ($field as $item) {
                if (isset($data[$item])) {
                    $result[$item] = $data[$item];
                }
            }
            return $result;
        } else {
            return isset($data[$field]) ? $data[$field] : "";
        }
    }

    public static function loadRowData($id) {
            $data = static::find()->where(['id'=>$id,'status'=>self::STATUS_PASS])->andWhere(['<=',"release_at",time()])->asArray()->one();
        return $data;
    }

    /**
     * 获取已发布的文章
     * @param $id
     * @return array
     */
    public static function loadReleaseArticle($id) {
            $data = static::find()->where("id=:id",[":id"=>$id])->andWhere(['<=',"release_at",time()])->asArray()->one();
        return $data;
    }

    public static function loadPreviewArticle($id) {
        return static::find()->where("id=:id",[":id"=>$id])->asArray()->one();
    }

    public static function loadPreview($id) {
            $data = static::find()->where(["id" => $id])->asArray()->one();
        return $data;
    }

    public static function getFavoriteArticle($num) {
        $where = ['and'];
        $where[] = ['=','status',self::STATUS_PASS];
        $where[] = ['<=','release_at',time()];
        return static::find()->select('id,title')->where($where)->orderBy('like_total desc,release_at asc')->asArray()->limit($num)->all();
    }

    public static function getNewArticle($num) {
        $where = ['and'];
        $where[] = ['=','status',self::STATUS_PASS];
        $where[] = ['<=','release_at',time()];
        return static::find()->select('id,title')->where($where)->orderBy('release_at desc')->asArray()->limit($num)->all();
    }


    /*
     * 增加文章阅读量
     */
    public static function viewerIncrement($id,$base = 1) {
        $model = static::findOne($id);
        if (!$model) {
            return false;
        }
        if ($base == 1) {
            return $model->updateCounters(["view_total"=>$base]);
        }
        return $model->updateCounters(["view_total"=>$base,"rabbit_total"=>$base]);
    }

    /*
     * 增加用户赞同量
     */
    public static function likerIncrement($id,$base = 1) {
        $model = static::findOne($id);
        if (!$model) {
            return false;
        }
        if ($base == 1) {
            return $model->updateCounters(["like_total"=>$base]);
        }
        return $model->updateCounters(["like_total"=>$base,"like_rabbit_total"=>$base]);
    }

    /**
     * 收藏数自增
     * @param $id
     * @return bool
     */
    public static function collectIncrement($id) {
        $model = static::findOne($id);
        if (!$model) {
            return false;
        }
        return $model->updateCounters(["collect_total"=>1]);
    }

    /**
     * 收藏数自减
     * @param $id
     * @return bool
     */
    public static function collectReduction($id) {
        $model = static::findOne($id);
        if (!$model) {
            return false;
        }
        return $model->updateCounters(["collect_total"=>-1]);
    }



    /**
     * 收藏数自增
     * @param $id
     * @return bool
     */
    public static function linkIncrement($id) {
        $model = static::findOne($id);
        if (!$model) {
            return false;
        }
        return $model->updateCounters(["like_total"=>1]);
    }

    /**
     * 收藏数自减
     * @param $id
     * @return bool
     */
    public static function linkReduction($id) {
        $model = static::findOne($id);
        if (!$model) {
            return false;
        }
        return $model->updateCounters(["like_total"=>-1]);
    }


    /**
     * 收藏数自增
     * @param $id
     * @return bool
     */
    public static function commentIncrement($id) {
        $model = static::findOne($id);
        if (!$model) {
            return false;
        }
        return $model->updateCounters(["comment_total"=>1]);
    }

    /**
     * 收藏数自减
     * @param $id
     * @return bool
     */
    public static function commentReduction($id) {
        $model = static::findOne($id);
        if (!$model) {
            return false;
        }
        return $model->updateCounters(["comment_total"=>-1]);
    }



    /**
     * 删除未通过的文章
     * @param $aid
     * @return bool|int
     */
    public static function removeArticle($aid) {
        $model = static::find()->where(["id"=>$aid])
            ->andWhere(["!=","status",self::STATUS_PASS])
            ->one();
        if (!$model) {
            return false;
        }
        return $model->delete();
    }

    /**
     * 获取指定的文章
     * @param $ids
     */
    public static function getArticleByIds($ids) {
        $result = static::find()
            ->select("id,title,summary,cover_image,channel,is_rec,collect_total,status,created_at")
            ->where(["status"=>self::STATUS_PASS])
            ->andWhere(["<=","release_at",time()])
            ->andWhere(["in","id",$ids])->all();
        return $result;
    }


    public static function getCoverImage($id,$size="320x240") {
        $model = static::findOne($id);
        if (!$model) return "";
        $image = $model["image"];
        $result = $image ? $image->imgSrc($size):"";
        return $result;
    }

    /**
     * 首页推荐（编辑推荐）
     * @param int $cateId
     * @param int $page
     * @param int $pageSize
     * @param string $appEnd
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function arrIndexRecArticle($cateId=0,$page=1,$pageSize=10,$appEnd = Constant::END_MOBILE) {
            if ($cateId == 0) {
                $q = static::find()->select("id,title,summary,author_id,like_total,cate_id,comment_total,collect_total,created_at,updated_at,release_at")
                    ->where(["status"=>self::STATUS_PASS])
                    ->andWhere(["<=","release_at",time()])
                    ->andWhere(["&","is_rec",self::REC_INDEX])
                    ->orderBy("sort,release_at DESC");
            } else {
                $cate_id_sub = Category::getSubAll($cateId);
                $cate_id_sub[] = $cateId;
                $article_id_arr = ArticleCate::getArticleCate($cate_id_sub)?array_unique(ArticleCate::getArticleCate($cate_id_sub)):[0];
                $where = ['and'];
                $where[] = ['=','status',self::STATUS_PASS];
                $where[] = ['<=','release_at',time()];
                $where[] = ['in','id',$article_id_arr];
                $q = static::find()->select("id,title,summary,author_id,like_total,cate_id,comment_total,collect_total,created_at,updated_at,release_at")
                    ->where($where)
                    ->orderBy("sort,release_at DESC");
            }
            $data = self::arrListByPage($q,$page,$pageSize);
            if (count($data["rows"])) {
                foreach ($data["rows"] as $k => $v) {
                    foreach ($v as $kk=>$vv) {
                        if (is_null($v[$kk])) {
                            unset($data["rows"][$k][$kk]);
                        }
                    }
                    $cate_id = $cateId?:$v['cate_id'];
                    $data["rows"][$k]["imgUrl"] = $appEnd==Constant::END_FRONT?Article::getCoverImage($v['id'],"250x140"):Article::getCoverImage($v['id'],"240x180");//AttachmentService::getImgSrcById($v["id"]);
                    $data["rows"][$k]['created_at'] = time()-$v['release_at']>86400?date("Y-m-d",$v['release_at']):CommonUtil::formatTime($v['release_at']);
                    $data["rows"][$k]['author_name'] = Admin::getFieldById($v['author_id']);
                    $data["rows"][$k]['author_image'] = User::getUserFace($v['author_id']);
                    $data["rows"][$k]['cate_name'] = Category::getFieldById($cate_id,'cate_name');
                    $data["rows"][$k]['tags'] = TagService::getTagsByArticle($v['id']);
                    $data["rows"][$k]['user_url'] = CommonUtil::generateUrl($v['author_id'],Constant::ROUTE_USER);    //作者url
                    $data["rows"][$k]['title_url'] = CommonUtil::generateUrl($v['id'],Constant::ROUTE_ARTICLE);   //文章标题url
                    $data["rows"][$k]['cate_url'] = CommonUtil::generateUrl($cate_id,Constant::ROUTE_CATEGORY);   //cate_url
                }
        }
        return $data;
    }

    /**
     * 文章随机推荐
     * @param $aid
     * @param $tagStr (话题标签 1,2,3,4)
     * @param $page
     * @param $pageSize
     * @param $appEnd
     * @param $coverImage
     * @return array
     * 推荐(0不推荐1首页推荐2热门)
     */
    public static function arrRandomRecommend($aid=0,$tagStr="",$page=1,$pageSize=4,$coverImage='') {
        if (empty($tagStr)) {
            return self::arrHotArticle("hot",$page,$pageSize,$coverImage);
        }
        $tagArr = explode(",",$tagStr);
        $articleIds = TagsRelation::arrObjectIds($tagArr);
        if (!count($articleIds)){
            return self::arrHotArticle("random",$page,$pageSize,$coverImage);
        }
        shuffle($articleIds);
        if (in_array($aid,$articleIds)) {
            $articleIds = array_diff($articleIds,[$aid]);
        }
        $q = static::find()->select("id,title,summary,author_id,cate_id,created_at,release_at")->where(["status"=>self::STATUS_PASS])
            ->andWhere(["<=","release_at",time()])->andWhere(["in","id",$articleIds])->orderBy("release_at DESC");
        $data = self::arrListByPage($q,$page,$pageSize);
        if ($data["rows"]) {
            foreach ($data["rows"] as $kk =>$row) {
                foreach ($row as $k => $v) {
                    if (is_null($v)) {
                        unset($data["rows"][$kk][$k]);
                    }
                }
                $article_cate = Category::find()->where(['id'=>$row['cate_id']])->asArray()->one();
                $data["rows"][$kk]["cate_name"] = $article_cate['category']['cate_name'];
                $data["rows"][$kk]["imgUrl"] = self::getCoverImage($row["id"],$coverImage);
                $data["rows"][$kk]["link"] = CommonUtil::generateUrl($row['id'],Constant::ROUTE_ARTICLE);    //热门文章url
                $data["rows"][$kk]["created_at"] = CommonUtil::formatTime($row["release_at"]);
            }

            if ($data["total"] < $pageSize) {
                $data_ext = self::arrHotArticle("random",$page,$pageSize,$coverImage);
                $data["rows"] = array_merge($data["rows"],array_slice($data_ext["rows"],0,$pageSize - $data["total"]));
                $data["total"] += $pageSize - $data['total'];
            }
            return $data;
        }
        return self::arrHotArticle("random",$page,$pageSize,$coverImage);
    }


    /**
     * @param string $type   hot 热门, random随机
     * @param int $page
     * @param int $pageSize
     * @param string $coverImage
     * @return array|mixed
     */
    public static function arrHotArticle($type="hot",$page=1,$pageSize=6,$coverImage='') {
        $key = "hot:article:type:".$type.":page:".$page.":size:".$pageSize."image:".$coverImage;
        $data = CommonUtil::getCache(__CLASS__,$key);
        if (!$data) {
            if ($type == "hot") {
                $q = static::find()->select("id,title,summary,created_at,view_total,cate_id,release_at,cover_image")->where(["status" => self::STATUS_PASS])
                    ->andWhere(["<=", "release_at", time()])->andWhere(["&", "is_rec", self::REC_HOT])->orderBy("sort ASC,release_at DESC");
            } elseif ($type == "random") {
                $q = static::find()->select("id,title,summary,created_at,view_total,cate_id,release_at,cover_image")->where(["status" => self::STATUS_PASS])
                    ->andWhere(["<=", "release_at", time()])->orderBy("comment_total DESC");
            } else {
                $q = static::find()->select("id,title,summary,view_total,created_at,cate_id,release_at,cover_image")->where(["status" => self::STATUS_PASS])
                    ->andWhere(["<=", "release_at", time()])->orderBy("sort ASC,release_at DESC");
            }
            $data = self::arrListByPage($q, $page, $pageSize);
            if ($data["rows"]) {
                foreach ($data["rows"] as $kk => $row) {
                    foreach ($row as $k => $v) {
                        if (is_null($v)) {
                            unset($data["rows"][$kk][$k]);
                        }
                    }
                    $data["rows"][$kk]["tags"] = TagsRelation::getTagInfoByArtId($row["id"]);
                    $article_cate = Category::find()->where(['id' => $row['cate_id']])->asArray()->one();
                    $data["rows"][$kk]["cate_name"] = $article_cate['cate_name'];
                    $data["rows"][$kk]["created_at"] = CommonUtil::formatTime($row["created_at"]);
                    $data["rows"][$kk]["release_at"] = CommonUtil::formatTime($row["release_at"]);
                    $data["rows"][$kk]["link"] = CommonUtil::generateUrl($row['id'], Constant::ROUTE_ARTICLE);
                }
            }
            CommonUtil::setCache(__CLASS__,$key,$data,3600);
        }
        return $data;
    }



    /**
     * 获取发表的文章数量数量
     * @return int
     */
    public static function intArticleByUserId() {
        return static::find()->where(["status"=>self::STATUS_PASS])->andWhere(["<=","release_at",time()])->count();
    }

    /**
     * 获取文章基本信息
     * @param $article_id
     * @param $coverImage
     * @return array
     */
    public static function getBaseInfo($article_id,$coverImage='320x240') {
        $data = self::loadRowData($article_id);
        if (!$data || $data["status"] != self::STATUS_PASS || $data['release_at']>time()) return [];
        return [
            'title'=>$data["title"],
            'summary'=>$data["summary"],
            'content'=>$data["content"],
            'article_link' => CommonUtil::generateUrl($article_id,Constant::ROUTE_ARTICLE),
            "like_count"=> $data["like_total"],
            "comment_count"=>$data["comment_total"],
            "collect_count"=>$data["collect_total"],
            "cover_image" =>  AttachmentService::getImgSrcById($article_id,$coverImage),
        ];
    }

    /*
     * 按类型返回数据
     */
    public static function getDataByType($type,$num) {
        $key = "data:type:".$type;
        $where = ['and'];
        $where[] =["like", 'cate_id', $type];
        $where[] = ["status"=>self::STATUS_PASS];
        $return_arr = CommonUtil::getCache(__CLASS__,$key);
        if (!$return_arr) {
            $data = static::find()
                ->select("id,title,summary,cover_image,collect_total,like_total,cate_id,comment_total,created_at,updated_at,release_at")
                ->where($where)
                ->orderBy("is_rec DESC,sort,id DESC")
                ->asArray()
                ->limit($num)
                ->all();
            if ($data) {
                foreach ($data as $k=>$item) {
                    $return_arr['data'][$k] = $item;
                    $article_cate = Category::find()->where(['id'=>$item['cate_id']])->asArray()->one();
                    $return_arr["data"][$k]["cate_name"] = $article_cate['cate_name'];
                    $return_arr["data"][$k]["tags"] = TagsRelation::getTagInfoByArtId($item["id"]);
                    $return_arr["data"][$k]["created_at"] = CommonUtil::formatTime($item["created_at"]);
                    $return_arr["data"][$k]["release_at"] = CommonUtil::formatTime($item["release_at"]);
                    $return_arr['data'][$k]["url"] = CommonUtil::generateUrl($item['id'],Constant::ROUTE_ARTICLE);
                }
            }
            CommonUtil::setCache(__CLASS__,$key,$return_arr,300);
        }
        return $return_arr;
    }


    /**
     * 找出 $day 天内的已发布的文章
     * @param $day
     * @return array
     */
    public static function getReleaseArticleByDay($day) {
        $endDay = time();
        $startDay = $endDay - (3600 * 24 * $day);
        $result = static::find()->select("id,release_at")->where("status=:sta",[":sta"=>self::STATUS_PASS])
            ->andWhere(["between","release_at",$startDay,$endDay])->andWhere(["<=","release_at",time()])->asArray()->all();
        return $result;
    }


    public static function getAllArticle($flag = true) {
        $result = $flag?static::find()->select("id,content,cate_id")->where("status=:sta",[":sta"=>self::STATUS_PASS])->andWhere(["<=","release_at",time()])->asArray()->all():static::find()->select("id,content,cate_id")->asArray()->all();
        return $result;
    }

    public static function findLenovoWord($uname)
    {
        $data = static::find()->select(["id", "title"])->where(["status" => self::STATUS_PASS])->andWhere(["<=","release_at",time()])->andWhere(["like", "title", $uname])->asArray()->all();
        return $data;
    }

    /**
     * 更新字段
     * @param $id
     * @param $filed
     * @param $data
     * @return bool
     */
    public static function saveArticleField($id,$filed,$data) {
        $model = static::findOne($id);
        if (!$model || !$filed) {
            return false;
        }
        if($data==static::STATUS_PASS){
            $model->release_at = time();
        }
        $model->$filed = $data;
        if (!$model->update()) {
            return false;
        }
        return true;
    }
    public static function findArticleByCate($cate_id,$page,$pageSize){
        $key = "article:cate:article:by:id:".$cate_id;
        $data = CommonUtil::getCache(__CLASS__,$key);
        if(!$data) {
            $q = static::find()->select("id,title,cover_image,summary,cate_id,created_at,release_at")->where(["status" => self::STATUS_PASS])->andWhere(["like", "cate_id", $cate_id])
                ->andWhere(["<=", "release_at", time()])->orderBy("release_at DESC");
            $data = self::arrListByPage($q, $page, $pageSize);
            if ($data["rows"]) {
                foreach ($data["rows"] as $kk => $row) {
                    foreach ($row as $k => $v) {
                        if (is_null($v)) {
                            unset($data["rows"][$kk][$k]);
                        }
                    }
                    $article_cate = Category::find()->where(['id' => $row['cate_id']])->asArray()->one();
                    $data["rows"][$kk]["cate_name"] = $article_cate['cate_name'];
                    $data["rows"][$kk]["tags"] = TagsRelation::getTagInfoByArtId($row["id"]);
                    $data["rows"][$kk]["created_at"] = CommonUtil::formatTime($row["release_at"]);
                    $data["rows"][$kk]["release_at"] = CommonUtil::formatTime($row["release_at"]);
                    $data["rows"][$kk]["link"] = CommonUtil::generateUrl($row['id'], Constant::ROUTE_ARTICLE);
                }
            }
            CommonUtil::setCache(__CLASS__,$key,$data);
        }
        return $data;
    }
}
